package com.ruoyi.location.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.location.repository.oss.OssRepository;
import com.ruoyi.location.service.AppService;
import com.ruoyi.location.domain.quickreport.util.RandomNumGenerator;
import com.ruoyi.location.vo.req.UserNameUpdateReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/location/user/")
@Slf4j
public class UserController extends BaseController {

    @Autowired
    private AppService appService;
    @Autowired
    private OssRepository ossRepository;

    @PostMapping("/name/update")
    @ResponseBody
    public AjaxResult login(@RequestBody UserNameUpdateReq req)
    {
        appService.updateUserInfo(req);
        return success();
    }

    @PostMapping("/avatar/upload")
    public AjaxResult uploadAvatar(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "userId", required = false) Long userId
    ) {
        try {
            // 验证文件
            validateFile(file);
            if (userId == null) {
                userId = ShiroUtils.getUserId();
            }
            // 上传到 OSS
            String name = userId + "-" + RandomNumGenerator.generateRandomNumber(9999);
            String avatarUrl = ossRepository.uploadAvatar(file, name);

            // 更新用户头像URL
            UserNameUpdateReq req = new UserNameUpdateReq();
            req.setUserId(userId);
            req.setAvatar(avatarUrl);
            appService.updateUserInfo(req);

            Map<String, String> data = new HashMap<>();
            data.put("url", avatarUrl);
            return AjaxResult.success("success", data);
        } catch (Exception e) {
            log.error("上传头像失败", e);
            return AjaxResult.error(e.getMessage());
        }
    }


    private void validateFile(MultipartFile file) {
        // 检查文件大小
        if (file.getSize() > 500 * 1024) { // 5MB
            throw new IllegalArgumentException("文件大小不能超过500KB");
        }

        // 检查文件类型
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            throw new IllegalArgumentException("只能上传图片文件");
        }

        // 支持的图片格式
        List<String> allowedTypes = Arrays.asList(
                "image/jpeg", "image/png"
        );
        if (!allowedTypes.contains(contentType)) {
            throw new IllegalArgumentException("不支持的图片格式");
        }
    }

}
